﻿using Farming.Domain.CustomClass;
using Farming.Repository;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Net.Http;
using System.Security.Claims;
using System.Text;

namespace Farming.WebApi
{
    public class CustomActionFilterAsyncAttribute : IAsyncActionFilter
    {
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            // 执行动作并获取结果
            var resultContext = await next();
        
            // 确保结果是 OkObjectResult 类型
          // if (resultContext.Result is OkObjectResult okResult)
            
                //// 从 OkObjectResult 中获取数据
                //var model = okResult.Value;

                //// 假设 model 是某个具有 Value 属性的对象
                //var valueProperty = model.GetType().GetProperty("value");

               // if (valueProperty != null)
                //{
                    //var value = valueProperty.GetValue(model);
                    // 开始时间，用于计算响应时长
                    var startTime = DateTime.Now;
                    // 计算响应时长
                    var duration = DateTime.Now - startTime;

                    // 获取 HttpContext
                    var httpContext = resultContext.HttpContext;

                    // 获取请求地址
                    var requestUrl = $"{httpContext.Request.Scheme}://{httpContext.Request.Host}{httpContext.Request.Path}{httpContext.Request.QueryString}";

                    // 获取用户 IP 地址
                    var userIp = httpContext.Connection.RemoteIpAddress?.ToString();

                    // 获取浏览器类型
                    var userAgent = httpContext.Request.Headers["User-Agent"].ToString();

                    // 获取请求参数（查询字符串和请求体）
                    var queryParameters = httpContext.Request.Query.ToDictionary(k => k.Key, v => v.Value.ToString());
                    string requestBody = null;

                    // 如果是 POST 请求，可以读取请求体（需要确保只读取一次）
                    if (httpContext.Request.Method == HttpMethods.Post)
                    {
                        httpContext.Request.EnableBuffering();
                        using (var reader = new StreamReader(httpContext.Request.Body, Encoding.UTF8, leaveOpen: true))
                        {
                            requestBody = await reader.ReadToEndAsync();
                            // Reset the body stream position for further processing
                            httpContext.Request.Body.Position = 0;
                        }
                    }

                    // 响应状态码
                    var statusCode = resultContext.HttpContext.Response.StatusCode;
                  
                    // 获取异常信息（如果有的话）
                    var exception = resultContext.Exception;
                    var logType = exception == null ? "系统" : "异常";
                    // 现在可以使用 value 了
                    var actionAdd = context.HttpContext.RequestServices.GetRequiredService<Repository<CustomActionModel>>();
                    var httpContextAccessor = context.HttpContext.RequestServices.GetRequiredService<IHttpContextAccessor>();
                    var claimsPrincipal = httpContextAccessor.HttpContext.User;
                    var customClaimType = "id";
                    var userId = claimsPrincipal.FindFirst(customClaimType)?.Value;
                    var username = claimsPrincipal.FindFirst(ClaimTypes.Name)?.Value;


                    CustomActionModel customActionModel = new CustomActionModel();
                    customActionModel.CActionTime = DateTime.Now;
                    customActionModel.CActionName = username;
                    customActionModel.CARequestAddress = requestUrl;
                    customActionModel.CALoginType = logType;
                    customActionModel.CAResponseStatus = statusCode.ToString();
                    customActionModel.CAResponselong = Convert.ToInt32(duration.TotalSeconds);
                    customActionModel.CARequestParams = queryParameters.ToString();
                    customActionModel.CAResponseParams = null;
                    customActionModel.CAErrorExpetion =null;
                    customActionModel.CAUserIp = userIp;
                    customActionModel.CABrowserType = userAgent;
                    actionAdd.InsertAsync(customActionModel);


                    // 这里可以继续进行其他操作
                }
            
        //}
    }
    
}
